<!DOCTYPE html>
<script src='../resources/testharness.js'></script>
<script src='../resources/testharnessreport.js'></script>
<script src='resources/shadow-dom.js'></script>
<script src='resources/focus-utils.js'></script>
<style>
div { background-color: white; }
div:focus { background-color: green; }
</style>
<body>
<div id='sandbox'></div>
</body>
<script>
'use strict';

// Test if :focus matching state of shadow host is properly handled in case of DOM mutation.

function buildTree(parent, delegatesFocus)
{
    parent.innerHTML = '<div id="host"></div><div id="dest"></div>';
    let host = parent.querySelector('#host');
    host.attachShadow({mode: 'open', delegatesFocus: delegatesFocus});
    host.shadowRoot.innerHTML = '<input id="input">';   
}

let sandbox = document.getElementById('sandbox');

test(() => {
    buildTree(sandbox, false);
    const host = getNodeInComposedTree('host');
    const input = getNodeInComposedTree('host/input');
    const dest = getNodeInComposedTree('dest');

    assert_background_color('host', 'rgb(255, 255, 255)');
    input.focus();
    assert_background_color('host', 'rgb(255, 255, 255)');
    dest.appendChild(input);
    assert_background_color('host', 'rgb(255, 255, 255)');
    input.focus();
    host.shadowRoot.appendChild(input);
    assert_background_color('host', 'rgb(255, 255, 255)');
}, '(1/2) DOM mutation across shadow boundary with delegatesFocus=false');

test(() => {
    buildTree(sandbox, true);
    const host = getNodeInComposedTree('host');
    const input = getNodeInComposedTree('host/input');
    const dest = getNodeInComposedTree('dest');

    assert_background_color('host', 'rgb(255, 255, 255)');
    input.focus();
    assert_background_color('host', 'rgb(0, 128, 0)');
    dest.appendChild(input);
    assert_background_color('host', 'rgb(255, 255, 255)');
    input.focus();
    host.shadowRoot.appendChild(input);
    // appendChild() will blur the focus from input element, thus input is no longer focused.
    assert_background_color('host', 'rgb(255, 255, 255)');
}, '(2/2) DOM mutation across shadow boundary with delegatesFocus=true');
</script>
